<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :data="depts" :props="defaultProps">
        <template #default="{ data }">
          <el-row style="width: 100%;">
            <el-col :span="20">
              {{ data.name }}
            </el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="12">{{ data.managerName||'李四' }}</el-col>
                <el-col :span="12">
                  <!-- 需要一个elementui 下拉菜单组件 -->
                  <el-dropdown @command="handleCommand($event,data.id)">
                    <span>
                      操作
                      <i class="el-icon-arrow-down" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                        <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                        <el-dropdown-item command="del">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <!-- <AddDept :show-add-dept.sync="showAddDept" /> -->
      <el-dialog :visible.sync="showAddDept" :title="title" @close="handleClose">
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="addForm.code" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <el-select v-model="addForm.managerId" placeholder="请输入">
              <el-option v-for="item in managerList" :key="item.id" :value="item.id" :label="item.username" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="addForm.introduce" type="textarea" placeholder="请输入" />
          </el-form-item>
          <el-form-item label-width="0" style="display: flex;justify-content: center;">
            <el-button type="primary" @click="submit">确定</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>

      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addDepartments, editDepartment, getDepartDetail, getDepartments, getManagerList, deleteDepartment } from '@/api/department'

import { transList2TreeData } from '@/utils'
// import AddDept from './components/add-dept.vue'

export default {
  name: 'Department',
  components: {
    // AddDept
  },
  data() {
    return {
      list: [],
      managerList: [], // 部门负责人列表(需要请求后端数据)
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showAddDept: false,
      addForm: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      }, // 添加部门的表单数据  字段和后端对齐
      rules: {
        name: [
          { required: true, message: '你还不填', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名字的长度在 2 到 10 个字符', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            let temp = this.list
            if (this.addForm.id) {
              temp = temp.filter(item => item.id !== this.addForm.id)
            }
            if (temp.some(item => item.name === value)) {
              callback(new Error('和已有部门的名字重复'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '你还不填', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码的长度在 2 到 10 个字符', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            let temp = this.list
            if (this.addForm.id) {
              temp = temp.filter(item => item.id !== this.addForm.id)
            }
            if (temp.some(item => item.code === value)) {
              callback(new Error('和已有部门的编码重复'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '你还不填', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '你还不填', trigger: 'blur' }
        ]
      }, // 添加部门的规则
      parentId: null // 父级id(用于添加部门)
    }
  },
  computed: {
    title() {
      return this.addForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getDepartments()
    this.getManagerList()
  },
  methods: {
    // 清空数据
    handleClose() {
      this.$refs.addForm.resetFields()
      this.addForm = {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      }
    },
    // 请求下拉选择对话框的管理员数据
    getManagerList() {
      getManagerList().then(res => {
        this.managerList = res
      })
    },
    handleCommand(type, id) {
      // 添加
      // console.log(111)
      if (type === 'add') {
        // console.log(111)
        this.showAddDept = true
        this.parentId = id // 存一下这行部门的id => 这是即将添加的子部门的pid
      }
      if (type === 'edit') {
        // 修改
        // console.log(222)
        this.showAddDept = true
        this.parentId = id// 存id => 编辑部门时获取部门详情的id
        this.getDepartDetail()
      }
      if (type === 'del') {
        // 删除
        // console.log(333)
        this.parentId = id
        // this.deleteDepartment()
        // 这里是二次确认
        this.$confirm('此操作将永久删除该部门, 是否继续?', '警告', {
          cancelButtonText: '我想想', // 配置取消按钮文字
          type: 'warning'// 配置图标
        }).then(() => {
          this.deleteDepartment()
        }).catch(() => {
          console.log('取消')
        })
      }
    },
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
      this.getDepartments()
      this.$message.success('删除成功')
    },
    // 根据部门id获取详情
    async getDepartDetail() {
      // 回显 将后端返回的详情数据 赋值 给表单  表单和页面做了双绑
      const res = await getDepartDetail(this.parentId)
      this.addForm = res
    },

    async getDepartments() {
      const res = await getDepartments()
      this.list = res// 单独备份一个数据用于查询是否重复
      this.list = res
      this.depts = transList2TreeData(res, 0)
    },
    submit() {
      // 整体校验 =>封装api接口 请求后端 => 提示 => 关闭对词诓 => 清空 => 重新请求重新渲染(调用函数)
      this.$refs.addForm.validate(async isOk => {
        if (isOk) {
          if (this.addForm.id) {
            await editDepartment(this.addForm)
            this.$message.success('编辑成功')
          } else {
            await addDepartments({
              ...this.addForm,
              pid: this.parentId
            })
            this.$message.success('添加成功')
          }

          this.getDepartments()

          this.showAddDept = false
          // this.$refs.addForm.resetFields()
          this.handleClose() // 清空数据
        }
      })
    }
  }
}
</script>
